package com.JFapp.service.impl;

import com.JFapp.constants.SystemConstants;
import com.JFapp.domain.dto.CategoryDto;
import com.JFapp.domain.entity.Article;
import com.JFapp.domain.entity.Category;
import com.JFapp.domain.entity.ResponseResult;
import com.JFapp.domain.vo.CategoryVo;
import com.JFapp.domain.vo.PageVo;
import com.JFapp.eumns.AppHttpCodeEnum;
import com.JFapp.exception.SystemException;
import com.JFapp.mapper.CategoryMapper;
import com.JFapp.service.ArticleService;
import com.JFapp.service.CategoryService;
import com.JFapp.utils.BeanCopyUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * (Category)表服务实现类
 *
 * @author makejava
 * @since 2024-03-13 19:20:35
 */
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private ArticleService articleService;

    @Override
    public ResponseResult getCategoryList() {
        //查询文章表，状态为已发布
        LambdaQueryWrapper<Article> articleWrapper=new LambdaQueryWrapper<>();
        articleWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        List<Article> articles=articleService.list(articleWrapper);
        //获取文章的分类ID，且去重(Set集合)
        Set<Long> categoryIds=articles.stream()
                .map(article -> article.getCategoryId())
                .collect(Collectors.toSet());
        //查询分类表,并且判断分类正常
        List<Category> categories = listByIds(categoryIds);
        categories = categories.stream().filter(category -> SystemConstants.CATEGORY_STATUS_NORMAL.equals(category.getStatus()))
                .collect(Collectors.toList());
        // 封装vo
        List<CategoryVo> CategoryVo= BeanCopyUtils.copyBeanList(categories, CategoryVo.class);
        return ResponseResult.okResult(CategoryVo);
    }

    @Override
    public ResponseResult selectCategory(Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Category> wrapper = queryWrapper.select().eq(Category::getDelFlag,SystemConstants.FLAG);
        Page page= new Page<>(pageNum,pageSize);
        page(page,wrapper);
        List<Category> records = page.getRecords();
        List<Category> category = BeanCopyUtils.copyBeanList(records, Category.class);
        PageVo pageVo = new PageVo(category,page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult addCategory(CategoryDto categoryDto) {
        Category category = BeanCopyUtils.copyBean(categoryDto, Category.class);
        if (StringUtils.hasText(categoryDto.getParentName())){
            Long pid = selectCategoryByName(categoryDto.getParentName());
            category.setPid(pid);
        }
        baseMapper.insert(category);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateCategory(Category category) {

        if (category.getPid()!=null) {
            LambdaUpdateWrapper<Category> updateWrapper=new LambdaUpdateWrapper<>();
            LambdaUpdateWrapper<Category> wrapper = updateWrapper.eq(Category::getId,category.getId());
            update(category,wrapper);
        } else {
            throw new SystemException(AppHttpCodeEnum.PID_ERROR);
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult deleteCategory(Long id) {
        Category category = baseMapper.selectById(id);
        category.setDelFlag(SystemConstants.DEL_FLAG);
        updateById(category);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getCategoryDetail(Long id) {
        Category category = baseMapper.selectById(id);
        return ResponseResult.okResult(category);
    }

    @Override
    public ResponseResult getListAllCategory() {
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Category> wrapper = queryWrapper.select().eq(Category::getStatus, SystemConstants.CATEGORY_STATUS_NORMAL).eq(Category::getDelFlag, SystemConstants.NOT_DELETE);
        List<Category> list = list(wrapper);
        return ResponseResult.okResult(list);

    }

    @Scheduled(cron = " 0 0 1 L * ?  ") //每月最后一天1点触发
    public void deleteCategory(){
        LambdaQueryWrapper<Category> queryWrapper= new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Category> wrapper = queryWrapper.select().eq(Category::getDelFlag, SystemConstants.DEL_FLAG);
        baseMapper.delete(wrapper);
    }

    private Long selectCategoryByName(String parentName) {
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Category> wrapper = queryWrapper.select(Category::getId).eq(Category::getName, parentName);
        Category category = baseMapper.selectOne(wrapper);
        return category.getId();
    }


}
